package org.ns.tomdog.server.support;

import org.ns.tomdog.server.*;
import org.ns.tomdog.servlet.HttpServlet;
import org.ns.tomdog.servlet.HttpServletRequest;
import org.ns.tomdog.servlet.HttpServletResponse;
import org.ns.tomdog.utils.HttpParse;

import java.io.File;

public class HttpProtocolAdapter implements ProtocolAdapter {

    private Connector connector;

    public HttpProtocolAdapter(Connector connector) {
        this.connector = connector;
    }

    @Override
    public void service(ServerRequest req, ServerResponse resp) {

        String url = req.getUrl();
        String method = req.getMethod();
        String host = req.getHeader("Host");
        // application/json
        // multipart/form-data
        // application/x-www-form-urlencoded
        // String contentType = getContentType(req);
        Container container = connector.getServer().getContainer();

        WebAppContainer webAppContainer = container.getWebAppContainer(host);
        if (webAppContainer == null) { // 404
            resp.setStatus(404);
            resp.setVersion(req.getVersion());
            resp.setError("NOT_FOUND_APP");
            return;
        }


        WebAppContext webAppContext = webAppContainer.getWebAppContext(url);
        if (webAppContext == null) { // 404
            resp.setStatus(404);
            resp.setVersion(req.getVersion());
            resp.setError("NOT_FOUND_CONTEXT");
            return;
        }
        String path = webAppContext.getPath();
        String contextPath = webAppContext.getContextPath();
        HttpServletRequest request = new HttpServletRequest(req, contextPath);
        HttpServletResponse response = new HttpServletResponse(resp);
        MapperWrapper handlerWrapper = webAppContext.getHandlerWrapper(url);

        if (handlerWrapper == null) {
            // 获取本地文件
            // 本地文件也不存在则返回404
            File file = new File(path, url.substring(contextPath.length()));
            if (!HttpParse.localFileOut(file, resp)) {
                resp.setStatus(404);
                resp.setVersion(req.getVersion());
                resp.setError("NOT_FOUND");
            }
        } else {
            HttpServlet httpServlet = handlerWrapper.getHttpServlet();
            if (method.toLowerCase().equals("get")) {
                httpServlet.doGet(request, response);
            } else {
                httpServlet.doPost(request, response);
            }
        }

    }

    private String getContentType(ServerRequest req) {
        String contentType = req.getHeader("Content-Type");
        int index = contentType.indexOf(";");
        if (index == -1) {
            return contentType.trim();
        } else {
            return contentType.substring(0, index).trim();
        }
    }
}
